import Vue from 'vue'
import Router from 'vue-router'

import Index from '@/views/index/Index.vue'
import Home from '@/views/center/Home.vue'
import Article from '@/components/Article.vue'
import ArticleDetail from '@/components/ArticleDetail.vue'
import Error from '@/views/error/Error.vue'
import Forbidden from '@/views/error/Forbidden.vue'
import BaiduHot from '@/components/BaiduHot.vue'

Vue.use(Router)

let originPush = Router.prototype.push
let originReplace = Router.prototype.replace
// 重写push/replace
// 第一个参数：告诉原来的push方法，往哪里跳转（传递哪些参数）
// 第二个参数：成功的回调
// 第三个参数：失败的回调
// call/apply区别
// 相同点：都可以调用函数一次，都可以篡改函数的上下文(this）一次‘
// 不同点：call/apply传递参数：call传递参数用逗号隔开，apply方法执行，传递数组
Router.prototype.push = function (location, resolve, reject) {
    if (resolve && reject) {
        originPush.call(this, location, resolve, reject)
    } else {
        originPush.call(
            this,
            location,
            () => { },
            () => { }
        )
    }
}
Router.prototype.replace = function (location, resolve, reject) {
    if (resolve && reject) {
        originReplace.call(this, location, resolve, reject)
    } else {
        originReplace.call(
            this,
            location,
            () => { },
            () => { }
        )
    }
}

const routes = [
    {
        path: '/error',
        name: 'Error',
        component: Error,
        meta: {
            title: '异常提醒'
        }
    },
    {
        path: '/forbidden',
        name: 'Forbidden',
        component: Forbidden,
        meta: {
            title: '黑名单提醒'
        }
    },
    {
        path: '/',
        name: 'Index',
        component: Index,
        redirect: '/home',
        meta: {
            title: '主页'
        },
        children: [
            {
                path: '/home',
                name: 'Home',
                component: Home,
                meta: {
                    title: '主页'
                }
            },
            {
                path: '/article',
                name: 'Article',
                component: Article,
                meta: {
                    title: '列表'
                }
            },
            {
                path: '/articleDetail',
                name: 'ArticleDetail',
                component: ArticleDetail,
                meta: {
                    title: '详情'
                }
            },
            {
                path: '/baiduHot',
                name: 'BaiduHot',
                component: BaiduHot,
                meta: {
                    title: '实时热点'
                }
            }
        ]
    }
]

export default new Router({
    // mode: 'history',
    routes: routes,
    scrollBehavior (to, from, savePosition) {
        // 如果不是查看详情路由，则页面跳转到对应的顶部
        return {
            x: 0,
            y: 0
        }
    }
})
